package com.lzx.adx.report.support.strategy.media;

import cn.hutool.core.util.URLUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.annnotions.MediaType;
import com.lzx.adx.report.constant.MediaChannelConstant;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.model.hc.HuiChuanRequest;
import com.lzx.adx.report.util.URLEncoderDecoderTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

@Component
@Slf4j
@MediaType(MediaChannelConstant.HUI_CHUAN)
public class HuiChuanCallBackStrategy extends AbstractCallback{
    @Override
    public ResponseEntity callback(ReportDTO reportDTO, AccountDTO accountDTO, String callType, String ts) {
        boolean base = base(reportDTO, accountDTO, callType, ts);
        if(!base){
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }
        String sspExtend = accountDTO.getSspExtend();
        JSONObject jsonObject = JSONObject.parseObject(sspExtend);
        String eventType = jsonObject.getString(callType);

        String decodeUrl = URLEncoderDecoderTool.decodeURL(reportDTO.getCallback());
        //2.回调渠道，调用快手回传接口
        Map<String, Object> reqParams = new HashMap<>();
        reqParams.put("type", eventType);
        reqParams.put("imei_sum", reportDTO.getImei());
        reqParams.put("oaid", reportDTO.getOaid());
        reqParams.put("event_time", ts);
        //组装参数和url
        String finalUrl = decodeUrl + "&" + URLUtil.buildQuery(reqParams, StandardCharsets.UTF_8);
        log.info("dspId{}请求流水号{}回调汇川完整地址为：{}", reportDTO.getDspId(), reportDTO.getDspId(), finalUrl);
        String result = HttpUtil.createGet(finalUrl).execute().body();
        log.info("dspId{}请求流水号{} 回调汇川结果为：{}", reportDTO.getDspId(), reportDTO.getDspId(), result);
        return ResponseEntity.ok(new Result());
    }
}
